#include <QtQml>

#include "utilsprivate.h"
#include "animationBinder.h"


AnimationBinder::AnimationBinder(QObject *parent):IdBinder(parent)
{
    setPropertys({"position","rotation"});
}

AnimationBinder::~AnimationBinder()
{

}

bool isKeyframeGroup(QObject* obj){
    auto meta = obj->metaObject();

    return UtilsPrivate::isBase(QByteArrayLiteral("QQuickKeyframeGroup"),meta);
}

BasePropertyBinder::BindDataList AnimationBinder::generateBindList()
{
    BasePropertyBinder::BindDataList ret;

    auto targetMap = UtilsPrivate::groupById(target());

    auto objs = source()->findChildren<QObject*>();

    auto props = propertys();

    for(auto i:objs)
    {
        if(isKeyframeGroup(i))
        {
            QObject* source = i->property("target").value<QObject*>();

            if(!source) continue;
            auto ctx = qmlContext(source);
            if(!ctx) continue;

            auto name = ctx->nameForObject(source);
            if(!targetMap.contains(name)) continue;
            auto target = targetMap[name];

            QString property = i->property("property").toString();

            if(!props.contains(property)) continue;

            auto p1 = source->metaObject()->property(source->metaObject()->indexOfProperty(property.toLocal8Bit()));
            auto p2 = target->metaObject()->property(target->metaObject()->indexOfProperty(property.toLocal8Bit()));

            if(!p1.isValid() || !p2.isValid())
            {
                continue;
            }

            BasePropertyBinder::BindData data;

            data.dst = target;
            data.dstProp = p2;
            data.src = source;
            data.srcProp = p1;

            ret << data;
        }
    }

    return ret;
}

void AnimationBinder::initialPropertys()
{
    auto sourceMap = UtilsPrivate::groupById(source());
    auto targetMap = UtilsPrivate::groupById(target());

    for(auto i:sourceMap.keys())
    {
        if(targetMap.contains(i))
        {
            auto dst = targetMap[i];
            auto src = sourceMap[i];
            auto dm = dst->metaObject();
            auto sm = src->metaObject();

            for(auto i :propertys())
            {
                auto sp = sm->property(sm->indexOfProperty(i.toUtf8()));
                auto dp = dm->property(dm->indexOfProperty(i.toUtf8()));

                if(sp.isValid() && dp.isValid())
                {
                    auto val = src->property(i.toUtf8());
                    dst->setProperty(i.toUtf8(),val);
                }
            }
        }
    }
}
